import React, { useState, useEffect } from 'react'
import { Plus, Edit2, Save, X, Trash2, Download, Calendar, ChevronLeft, ChevronRight, ChevronDown, Send } from 'lucide-react'
import { dailyWorkPlanAPI, personnelAPI } from '../services/api'

// 多选下拉组件
const MultiSelect = ({ options, value, onChange, placeholder }) => {
  const [isOpen, setIsOpen] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const dropdownRef = React.useRef(null)

  // 点击外部关闭下拉框
  React.useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false)
        setSearchTerm('')
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  const filteredOptions = options.filter(option => 
    option.label.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const handleToggleOption = (optionValue) => {
    const newValue = value.includes(optionValue)
      ? value.filter(v => v !== optionValue)
      : [...value, optionValue]
    onChange(newValue)
  }

  const displayText = value.length > 0 ? value.join(', ') : placeholder

  return (
    <div ref={dropdownRef} style={{ position: 'relative', width: '100%' }}>
      <div
        onClick={() => setIsOpen(!isOpen)}
        style={{
          border: '1px solid #ddd',
          borderRadius: '4px',
          padding: '8px',
          cursor: 'pointer',
          backgroundColor: 'white',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          fontSize: '14px',
          height: '36px',
          boxSizing: 'border-box'
        }}
      >
        <span style={{ 
          color: value.length > 0 ? '#333' : '#999',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap'
        }}>
          {displayText}
        </span>
        <ChevronDown size={14} style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.2s' }} />
      </div>
      
      {isOpen && (
        <div style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          right: 0,
          backgroundColor: 'white',
          border: '1px solid #ddd',
          borderTop: 'none',
          borderRadius: '0 0 4px 4px',
          maxHeight: '200px',
          overflowY: 'auto',
          zIndex: 9999,
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <input
            type="text"
            placeholder="搜索人员..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={{
              width: '100%',
              padding: '8px',
              border: 'none',
              borderBottom: '1px solid #eee',
              fontSize: '14px',
              outline: 'none'
            }}
            onClick={(e) => e.stopPropagation()}
          />
          {filteredOptions.map(option => (
            <div
              key={option.value}
              onClick={() => handleToggleOption(option.value)}
              style={{
                padding: '8px',
                cursor: 'pointer',
                backgroundColor: value.includes(option.value) ? '#e3f2fd' : 'white',
                borderBottom: '1px solid #f0f0f0',
                fontSize: '14px',
                display: 'flex',
                alignItems: 'center',
                gap: '8px'
              }}
            >
              <input
                type="checkbox"
                checked={value.includes(option.value)}
                onChange={() => {}}
                style={{ margin: 0 }}
              />
              {option.label}
            </div>
          ))}
          {filteredOptions.length === 0 && (
            <div style={{ padding: '8px', color: '#999', fontSize: '14px' }}>
              无匹配人员
            </div>
          )}
        </div>
      )}
    </div>
  )
}

// 时间格式转换函数：将ISO 8601格式转换为datetime-local格式
const formatDateTimeForInput = (isoString) => {
  if (!isoString) return ''
  try {
    const date = new Date(isoString)
    // 转换为本地时间并格式化为YYYY-MM-DDTHH:MM
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day}T${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式转换错误:', error)
    return ''
  }
}

// 反向转换函数：将datetime-local格式转换为ISO 8601格式
const formatDateTimeForAPI = (localString) => {
  if (!localString) return null
  try {
    // datetime-local格式: YYYY-MM-DDTHH:MM
    // 转换为ISO 8601格式
    const date = new Date(localString)
    return date.toISOString()
  } catch (error) {
    console.error('时间格式转换错误:', error)
    return null
  }
}

const DailyWorkPlan = () => {
  const [selectedType, setSelectedType] = useState('总览')
  
  // 实验类型配置
  const experimentTypes = [
    { key: '总览', label: '总览', color: '#3498db' },
    { key: '热学试验', label: '热学试验', color: '#e74c3c' },
    { key: '力学及电磁试验', label: '力学及电磁试验', color: '#f39c12' },
    { key: '专项工作', label: '专项工作', color: '#9b59b6' },
    { key: '其他', label: '其他', color: '#8e44ad' }
  ]

  // 人员信息状态
  const [personnel, setPersonnel] = useState([])

  // 试验计划数据状态
  const [experimentPlans, setExperimentPlans] = useState({})
  
  // 项目数据状态 - 新的数据结构
  const [projectData, setProjectData] = useState({
    '总览': [],
    '热学试验': [],
    '力学及电磁试验': [],
    '专项工作': [],
    '其他': []
  })
  
  // 加载状态
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  // 编辑状态
  const [editingCell, setEditingCell] = useState(null)
  const [editValue, setEditValue] = useState('')
  const [textareaRef, setTextareaRef] = useState(null)
  const [currentFocusedTextarea, setCurrentFocusedTextarea] = useState(null)

  // 日历选择器状态
  const [showCalendar, setShowCalendar] = useState(false)
  const [selectedDates, setSelectedDates] = useState([])
  const [calendarMonth, setCalendarMonth] = useState(new Date())
  const [isRangeSelection, setIsRangeSelection] = useState(false)
  const [rangeStart, setRangeStart] = useState(null)
  const [rangeEnd, setRangeEnd] = useState(null)

  // 加载人员信息
  const loadPersonnel = async () => {
    try {
      const data = await personnelAPI.getAll()
      setPersonnel(data.results || data || [])
    } catch (error) {
      console.error('加载人员信息失败:', error)
      setError('加载人员信息失败')
    }
  }

  // 加载工作计划数据
  const loadWorkPlans = async (dates = null) => {
    try {
      setLoading(true)
      let data
      
      if (dates && dates.length > 0) {
        // 如果有选择的日期，按日期范围加载
        const sortedDates = dates.sort()
        const startDate = sortedDates[0]
        const endDate = sortedDates[sortedDates.length - 1]
        data = await dailyWorkPlanAPI.getByDateRange(startDate, endDate)
      } else {
        // 否则加载最近7天的数据
        data = await dailyWorkPlanAPI.getRecentPlans()
      }
      
      // 将后端数据转换为前端projectData格式
      if (data && Array.isArray(data)) {
        const newProjectData = {
          '总览': [],
          '热学试验': [],
          '力学及电磁试验': [],
          '专项工作': [],
          '其他': []
        }
        
        data.forEach(project => {
          const experimentType = project.experiment_type
          if (newProjectData[experimentType]) {
            const projectItem = {
              id: project.id.toString(),
              date: project.date,
              project: project.project_name || '',
              workItems: project.work_items && project.work_items.length > 0 
                ? project.work_items.map(item => ({
                    content: item.content || '',
                    responsible: item.responsible || '',
                    participants: item.participants || '',
                    start_time: formatDateTimeForInput(item.start_time),
                    end_time: formatDateTimeForInput(item.end_time)
                  }))
                : [{
                    content: '',
                    responsible: '',
                    participants: '',
                    start_time: '',
                    end_time: ''
                  }]
            }
            
            // 如果是热学试验，添加值班人字段
            if (experimentType === '热学试验') {
              projectItem.duty_day = project.duty_day || ''
              projectItem.duty_night = project.duty_night || ''
            }
            
            newProjectData[experimentType].push(projectItem)
          }
        })
        
        setProjectData(newProjectData)
      }
      
      setExperimentPlans(data || {})
    } catch (error) {
      console.error('加载工作计划失败:', error)
      setError('加载工作计划失败')
    } finally {
      setLoading(false)
    }
  }

  // 保存工作计划到后端
  const saveWorkPlans = async (plansData) => {
    try {
      setLoading(true)
      await dailyWorkPlanAPI.bulkSave(plansData)
      console.log('工作计划保存成功')
    } catch (error) {
      console.error('保存工作计划失败:', error)
      setError('保存工作计划失败')
    } finally {
      setLoading(false)
    }
  }

  // 保存所有数据到数据库
  const handleSaveAllData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      // 准备要保存的数据
      const allProjects = []
      
      // 遍历所有实验类型的项目数据
      Object.keys(projectData).forEach(experimentType => {
        if (experimentType !== '总览') {
          projectData[experimentType].forEach(project => {
            if (project.project && project.workItems && project.workItems.length > 0) {
              // 过滤掉空的工作项
              const validWorkItems = project.workItems.filter(item => 
                item.content || item.responsible || item.participants
              )
              
              if (validWorkItems.length > 0) {
                // 转换工作项中的时间格式
                const convertedWorkItems = validWorkItems.map(item => ({
                  ...item,
                  start_time: formatDateTimeForAPI(item.start_time),
                  end_time: formatDateTimeForAPI(item.end_time)
                }))
                
                allProjects.push({
                  ...project,
                  experiment_type: experimentType,
                  workItems: convertedWorkItems
                })
              }
            }
          })
        }
      })
      
      if (allProjects.length === 0) {
        alert('没有可保存的数据')
        return
      }
      
      // 调用API保存数据
      await dailyWorkPlanAPI.bulkSave({ projects: allProjects })
      
      // 重新加载数据
      await loadWorkPlans(selectedDates.length > 0 ? selectedDates : null)
      
    } catch (error) {
      console.error('保存数据失败:', error)
      setError('保存数据失败: ' + (error.message || '未知错误'))
      alert('保存数据失败: ' + (error.message || '未知错误'))
    } finally {
      setLoading(false)
    }
  }

  // 钉钉机器人推送函数
  const handlePushToDingTalk = async () => {
    try {
      setLoading(true)
      setError(null)
      
      // 获取当前选项卡的数据
      const currentTypeData = projectData[selectedType]
      
      if (!currentTypeData || currentTypeData.length === 0) {
        alert('当前选项卡没有数据可提交')
        return
      }
      
      // 获取当前日期或选中的日期
      const getLocalDateString = () => {
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
      
      const targetDate = selectedDates.length > 0 ? selectedDates[0] : getLocalDateString()
      
      // 过滤当前日期的项目
      const todayProjects = currentTypeData.filter(project => project.date === targetDate)
      
      if (todayProjects.length === 0) {
        alert(`${targetDate} 没有 ${selectedType} 类型的项目数据可提交`)
        return
      }
      
      // 准备推送数据
      const pushData = {
        experiment_type: selectedType,
        date: targetDate,
        projects: todayProjects.map(project => ({
          id: project.id,
          project_name: project.project,
          duty_day: project.duty_day || '',
          duty_night: project.duty_night || '',
          work_items: project.workItems.filter(item => 
            item.content || item.responsible || item.participants
          ).map(item => ({
            content: item.content || '',
            responsible: item.responsible || '',
            participants: item.participants || '',
            start_time: formatDateTimeForAPI(item.start_time),
            end_time: formatDateTimeForAPI(item.end_time)
          }))
        }))
      }
      
      // 调用钉钉推送API
      await dailyWorkPlanAPI.pushToDingTalk(pushData)
      
    } catch (error) {
      console.error('钉钉推送失败:', error)
      setError('钉钉推送失败: ' + (error.message || '未知错误'))
      alert('钉钉推送失败: ' + (error.message || '未知错误'))
    } finally {
      setLoading(false)
    }
  }

  // 项目管理函数
  const addProject = (type) => {
    // 使用选中日期范围中的第一个日期，如果没有选中日期则使用今天
    const getLocalDateString = () => {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    const defaultDate = selectedDates.length > 0 
      ? selectedDates.sort()[0] 
      : getLocalDateString()
    
    const newProject = {
      id: Date.now().toString(),
      date: defaultDate,
      project: '',
      workItems: [{
        content: '',
        responsible: '',
        participants: '',
        start_time: '',
        end_time: ''
      }]
    }
    
    // 如果是热学试验，添加值班人字段
    if (type === '热学试验') {
      newProject.duty_day = ''
      newProject.duty_night = ''
    }
    
    setProjectData(prev => ({
      ...prev,
      [type]: [...prev[type], newProject]
    }))
  }

  const removeProject = async (type, projectId) => {
    try {
      // 检查项目是否是新建的（ID为时间戳字符串且较大，表示是前端生成的临时ID）
      const isNewProject = projectId.toString().length > 10 && parseInt(projectId) > 1000000000000
      
      if (!isNewProject) {
        // 如果是已保存的项目，调用后端API删除
        await dailyWorkPlanAPI.delete(projectId)
      }
      
      // 删除成功后更新前端状态
      setProjectData(prev => ({
        ...prev,
        [type]: prev[type].filter(project => project.id !== projectId)
      }))
    } catch (error) {
      console.error('删除项目失败:', error)
      setError('删除项目失败: ' + (error.message || '未知错误'))
    }
  }

  const updateProject = (type, projectId, field, value) => {
    setProjectData(prev => ({
      ...prev,
      [type]: prev[type].map(project => 
        project.id === projectId 
          ? { ...project, [field]: value }
          : project
      )
    }))
  }

  const addWorkItem = (type, projectId) => {
    setProjectData(prev => ({
      ...prev,
      [type]: prev[type].map(project => 
        project.id === projectId 
          ? { 
              ...project, 
              workItems: [...project.workItems, {
                content: '',
                responsible: '',
                participants: '',
                start_time: '',
                end_time: ''
              }]
            }
          : project
      )
    }))
  }

  const removeWorkItem = async (type, projectId, workIndex) => {
    try {
      // 先更新前端状态
      const updatedProjectData = { ...projectData }
      const project = updatedProjectData[type].find(p => p.id === projectId)
      if (!project) return
      
      // 删除指定的工作项
      const updatedWorkItems = project.workItems.filter((_, index) => index !== workIndex)
      
      // 检查项目是否是新建的（ID为时间戳字符串且较大，表示是前端生成的临时ID）
      const isNewProject = projectId.toString().length > 10 && parseInt(projectId) > 1000000000000
      
      if (!isNewProject) {
        // 如果是已保存的项目，调用后端API更新项目（这会同步删除工作项）
        const projectToSave = {
          id: project.id,
          date: project.date,
          experiment_type: type,
          project_name: project.project_name || '',
          duty_day: project.duty_day || '',
          duty_night: project.duty_night || '',
          work_items: updatedWorkItems.map((item, index) => ({
            content: item.content || '',
            responsible: item.responsible || '',
            participants: item.participants || '',
            order: index
          }))
        }
        
        await dailyWorkPlanAPI.patch(projectId, projectToSave)
      }
      
      // 更新前端状态
      setProjectData(prev => ({
        ...prev,
        [type]: prev[type].map(p => 
          p.id === projectId 
            ? { ...p, workItems: updatedWorkItems }
            : p
        )
      }))
    } catch (error) {
      console.error('删除工作项失败:', error)
      setError('删除工作项失败: ' + (error.message || '未知错误'))
    }
  }

  const updateWorkItem = (type, projectId, workIndex, field, value) => {
    setProjectData(prev => ({
      ...prev,
      [type]: prev[type].map(project => 
        project.id === projectId 
          ? { 
              ...project, 
              workItems: project.workItems.map((item, index) => 
                index === workIndex 
                  ? { ...item, [field]: value }
                  : item
              )
            }
          : project
      )
    }))
  }

  // 组件初始化时加载数据
  useEffect(() => {
    loadPersonnel()
    loadWorkPlans()
  }, [])

  // 当选择的日期改变时重新加载数据
  useEffect(() => {
    if (selectedDates.length > 0) {
      loadWorkPlans(selectedDates)
    }
  }, [selectedDates])

  // 获取星期几
  const getWeekDay = (dateString) => {
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const date = new Date(dateString)
    return weekDays[date.getDay()]
  }



  // 生成昨天和今天的日期
  const getRecentDates = () => {
    const dates = []
    const today = new Date()
    
    // 添加昨天
    const yesterday = new Date(today)
    yesterday.setDate(today.getDate() - 1)
    const yesterdayStr = yesterday.toISOString().split('T')[0]
    const yesterdayDayOfWeek = yesterday.getDay()
    const yesterdayIsWeekend = yesterdayDayOfWeek === 0 || yesterdayDayOfWeek === 6
    dates.push({
      date: yesterdayStr,
      weekDay: getWeekDay(yesterdayStr),
      isWeekend: yesterdayIsWeekend,
      isSpecialDay: yesterdayIsWeekend
    })
    
    // 添加今天
    const todayStr = today.toISOString().split('T')[0]
    const todayDayOfWeek = today.getDay()
    const todayIsWeekend = todayDayOfWeek === 0 || todayDayOfWeek === 6
    dates.push({
      date: todayStr,
      weekDay: getWeekDay(todayStr),
      isWeekend: todayIsWeekend,
      isSpecialDay: todayIsWeekend
    })
    
    return dates
  }

  // 日历相关函数
  const getDaysInMonth = (date) => {
    const year = date.getFullYear()
    const month = date.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    const daysInMonth = lastDay.getDate()
    const startingDayOfWeek = firstDay.getDay()
    
    const days = []
    
    // 格式化日期为本地日期字符串（避免时区问题）
    const formatLocalDate = (dateObj) => {
      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 添加上个月的日期（灰色显示）
    for (let i = startingDayOfWeek - 1; i >= 0; i--) {
      const prevDate = new Date(year, month, -i)
      days.push({
        date: formatLocalDate(prevDate),
        day: prevDate.getDate(),
        isCurrentMonth: false,
        isToday: false,
        isSelected: false,
        isInRange: false
      })
    }
    
    // 添加当前月的日期
    const today = formatLocalDate(new Date())
    for (let day = 1; day <= daysInMonth; day++) {
      const currentDate = new Date(year, month, day)
      const dateStr = formatLocalDate(currentDate)
      
      // 在范围选择模式下，需要考虑rangeStart和rangeEnd的状态
      let isSelected = false
      if (isRangeSelection) {
        // 范围选择模式下的选中状态逻辑
        if (rangeStart && rangeEnd) {
          // 已完成范围选择，显示范围内的所有日期
          isSelected = isDateInRange(dateStr)
        } else if (rangeStart) {
          // 只选择了起始日期，显示起始日期为选中状态
          isSelected = dateStr === rangeStart
        }
      } else {
        // 单选模式下的选中状态
        isSelected = selectedDates.includes(dateStr)
      }
      
      days.push({
        date: dateStr,
        day: day,
        isCurrentMonth: true,
        isToday: dateStr === today,
        isSelected: isSelected,
        isInRange: isDateInRange(dateStr)
      })
    }
    
    // 添加下个月的日期（灰色显示）
    const remainingDays = 42 - days.length // 6行 x 7天
    for (let day = 1; day <= remainingDays; day++) {
      const nextDate = new Date(year, month + 1, day)
      days.push({
        date: formatLocalDate(nextDate),
        day: nextDate.getDate(),
        isCurrentMonth: false,
        isToday: false,
        isSelected: false,
        isInRange: false
      })
    }
    
    return days
  }

  const isDateInRange = (dateStr) => {
    if (!rangeStart || !rangeEnd) return false
    const date = new Date(dateStr)
    const start = new Date(rangeStart)
    const end = new Date(rangeEnd)
    return date >= start && date <= end
  }

  const handleDateClick = (dateStr) => {
    if (isRangeSelection) {
      if (!rangeStart) {
        setRangeStart(dateStr)
        setRangeEnd(null)
      } else if (!rangeEnd) {
        const start = new Date(rangeStart)
        const end = new Date(dateStr)
        if (end < start) {
          setRangeStart(dateStr)
          setRangeEnd(rangeStart)
        } else {
          setRangeEnd(dateStr)
        }
        // 生成范围内的所有日期
        const dates = []
        const current = new Date(Math.min(start, end))
        const endDate = new Date(Math.max(start, end))
        while (current <= endDate) {
          // 使用本地时间格式化日期（避免时区问题）
          const year = current.getFullYear()
          const month = String(current.getMonth() + 1).padStart(2, '0')
          const day = String(current.getDate()).padStart(2, '0')
          dates.push(`${year}-${month}-${day}`)
          current.setDate(current.getDate() + 1)
        }
        setSelectedDates(dates)
      } else {
        // 重新开始选择
        setRangeStart(dateStr)
        setRangeEnd(null)
        setSelectedDates([])
      }
    } else {
      // 单选模式
      if (selectedDates.includes(dateStr)) {
        setSelectedDates(selectedDates.filter(d => d !== dateStr))
      } else {
        setSelectedDates([...selectedDates, dateStr])
      }
    }
  }

  const clearSelection = () => {
    setSelectedDates([])
    setRangeStart(null)
    setRangeEnd(null)
  }

  const applySelection = () => {
    setShowCalendar(false)
  }

  // 获取显示的日期数据
  const getDisplayDates = () => {
    if (selectedDates.length > 0) {
      return selectedDates.sort().map(dateStr => {
        const date = new Date(dateStr)
        const dayOfWeek = date.getDay()
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
        return {
          date: dateStr,
          weekDay: getWeekDay(dateStr),
          isWeekend: isWeekend,
          isSpecialDay: isWeekend
        }
      })
    }
    return getRecentDates()
  }

  // 导出Excel功能
  const exportToExcel = () => {
    const currentDates = getDisplayDates()
    
    if (selectedType === '总览') {
      // 总览表格导出
      exportOverviewToExcel(currentDates)
    } else {
      // 单个试验类型导出
      exportSingleTypeToExcel(currentDates, selectedType)
    }
  }

  // 导出总览表格
  const exportOverviewToExcel = (datesToExport) => {
    let csvContent = "data:text/csv;charset=utf-8,\uFEFF"
    
    // 表头
    const headers = [
      '日期',
      '热学试验-试验项目', '热学试验-工作内容', '热学试验-负责人', '热学试验-执行人', '热学试验-值班人(9点-21点/21点-9点)',
      '力学及电磁试验-试验项目', '力学及电磁试验-工作内容', '力学及电磁试验-负责人', '力学及电磁试验-执行人',
      '专项工作-试验项目', '专项工作-工作内容', '专项工作-负责人', '专项工作-执行人',
      '其他-试验项目', '其他-工作内容', '其他-负责人', '其他-执行人'
    ]
    csvContent += headers.join(',') + '\n'
    
    // 数据行
    datesToExport.forEach(dateInfo => {
      const row = [
        `"${dateInfo.date} (${dateInfo.weekDay})"`,
        `"${getValueByKey(`${dateInfo.date}.热学试验.project`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.热学试验.content`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.热学试验.responsible`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.热学试验.participants`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.热学试验.duty`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.力学及电磁试验.project`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.力学及电磁试验.content`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.力学及电磁试验.responsible`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.力学及电磁试验.participants`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.专项工作.project`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.专项工作.content`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.专项工作.responsible`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.专项工作.participants`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.其他.project`) || ''}"`
        `"${getValueByKey(`${dateInfo.date}.其他.content`) || ''}"`
        `"${getValueByKey(`${dateInfo.date}.其他.responsible`) || ''}"`
        `"${getValueByKey(`${dateInfo.date}.其他.participants`) || ''}"`
      ]
      csvContent += row.join(',') + '\n'
    })
    
    downloadCSV(csvContent, `日工作计划总览_${new Date().toISOString().split('T')[0]}.csv`)
  }

  // 导出单个试验类型
  const exportSingleTypeToExcel = (datesToExport, experimentType) => {
    let csvContent = "data:text/csv;charset=utf-8,\uFEFF"
    
    // 表头
    const headers = ['日期', '试验项目', '工作内容', '负责人', '执行人']
    if (experimentType === '热学试验') {
      headers.push('值班人')
    }
    csvContent += headers.join(',') + '\n'
    
    // 数据行
    datesToExport.forEach(dateInfo => {
      const row = [
        `"${dateInfo.date} (${dateInfo.weekDay})"`,
        `"${getValueByKey(`${dateInfo.date}.${experimentType}.project`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.${experimentType}.content`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.${experimentType}.responsible`) || ''}"`,
        `"${getValueByKey(`${dateInfo.date}.${experimentType}.participants`) || ''}"`
      ]
      if (experimentType === '热学试验') {
        row.push(`"${getValueByKey(`${dateInfo.date}.${experimentType}.duty`) || ''}"`) 
      }
      csvContent += row.join(',') + '\n'
    })
    
    downloadCSV(csvContent, `${experimentType}_${new Date().toISOString().split('T')[0]}.csv`)
  }

  // 下载CSV文件
  const downloadCSV = (csvContent, filename) => {
    const encodedUri = encodeURI(csvContent)
    const link = document.createElement("a")
    link.setAttribute("href", encodedUri)
    link.setAttribute("download", filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  // 开始编辑
  const startEdit = (key) => {
    const value = getValueByKey(key)
    setEditingCell(key)
    setEditValue(value || '')
  }

  // 获取值
  const getValueByKey = (key) => {
    const keys = key.split('.')
    let obj = experimentPlans
    for (let k of keys) {
      obj = obj?.[k]
    }
    return obj || ''
  }

  // 保存编辑
  const saveEdit = async () => {
    if (!editingCell) return
    
    const newPlans = { ...experimentPlans }
    const keys = editingCell.split('.')
    
    // 创建嵌套对象路径
    let current = newPlans
    for (let i = 0; i < keys.length - 1; i++) {
      if (!current[keys[i]]) {
        current[keys[i]] = {}
      }
      current = current[keys[i]]
    }
    
    current[keys[keys.length - 1]] = editValue
    
    // 更新本地状态
    setExperimentPlans(newPlans)
    
    // 保存到后端
    await saveWorkPlans(newPlans)
    
    setEditingCell(null)
    setEditValue('')
  }

  // 添加内容到当前编辑的值（在当前行下方添加新行）
  const addToContent = () => {
    if (!editingCell) return
    const currentValue = editValue || ''
    
    // 在当前内容后添加新行
    const newValue = currentValue + (currentValue ? '\n' : '')
    setEditValue(newValue)
    
    // 使用setTimeout确保textarea已经更新，然后设置光标位置到新行
    setTimeout(() => {
      if (textareaRef) {
        textareaRef.focus()
        const cursorPosition = newValue.length
        textareaRef.setSelectionRange(cursorPosition, cursorPosition)
      }
    }, 10)
  }

  // 删除当前行内容
  const deleteCurrentLine = () => {
    if (!editingCell) return
    
    const lines = editValue.split('\n')
    if (lines.length <= 1) {
      // 如果只有一行或没有内容，清空整个字段
      setEditValue('')
    } else {
      // 删除最后一行
      lines.pop()
      setEditValue(lines.join('\n'))
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingCell(null)
    setEditValue('')
  }

  // 渲染编辑单元格（只用于单个实验类型页面）
  const renderEditableCell = (key, placeholder = '', isSelect = false, selectOptions = []) => {
    const isEditing = editingCell === key
    const value = getValueByKey(key)
    
    if (isEditing) {
      if (isSelect) {
        return (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: '2px' }}>
            <div style={{ flex: 1, position: 'relative' }}>
              <textarea
                ref={setTextareaRef}
                value={editValue}
                onChange={(e) => setEditValue(e.target.value)}
                placeholder="请选择人员"
                rows={Math.max(1, editValue.split('\n').length)}
                style={{ 
                  width: '100%', 
                  padding: '4px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '4px',
                  fontSize: '14px',
                  resize: 'vertical',
                  minHeight: '20px'
                }}
              />
              {selectOptions.length > 0 && (
                <div style={{
                  position: 'absolute',
                  top: '100%',
                  left: 0,
                  right: 0,
                  background: 'white',
                  border: '1px solid #d9d9d9',
                  borderTop: 'none',
                  borderRadius: '0 0 4px 4px',
                  maxHeight: '120px',
                  overflowY: 'auto',
                  zIndex: 1000,
                  fontSize: '14px'
                }}>
                  {selectOptions.map(option => (
                    <div
                      key={option.value}
                      onClick={() => {
                        const currentLines = editValue.split('\n')
                        const lastLine = currentLines[currentLines.length - 1]
                        
                        if (lastLine.trim() === '') {
                          // 如果最后一行是空的，替换它
                          currentLines[currentLines.length - 1] = option.value
                        } else {
                          // 如果最后一行有内容，添加新行
                          currentLines.push(option.value)
                        }
                        
                        setEditValue(currentLines.join('\n'))
                      }}
                      style={{
                        padding: '4px 8px',
                        cursor: 'pointer',
                        borderBottom: '1px solid #f0f0f0'
                      }}
                      onMouseEnter={(e) => e.target.style.background = '#f5f5f5'}
                      onMouseLeave={(e) => e.target.style.background = 'white'}
                    >
                      {option.label}
                    </div>
                  ))}
                </div>
              )}
            </div>
            <button 
              onClick={addToContent} 
              title="添加行"
              style={{ 
                padding: '4px', 
                fontSize: '10px', 
                background: '#3498db', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              <Plus size={12} />
            </button>
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              ✕
            </button>
            <button 
              onClick={deleteCurrentLine} 
              title="删除当前行"
              style={{ 
                padding: '4px', 
                fontSize: '10px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              <Trash2 size={12} />
            </button>
          </div>
        )
      } else {
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
            <textarea
              ref={setTextareaRef}
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              placeholder={placeholder}
              rows={Math.max(1, editValue.split('\n').length)}
              style={{ 
                flex: 1, 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '14px',
                resize: 'vertical',
                minHeight: '20px'
              }}
            />
            <button 
              onClick={addToContent} 
              title="添加行"
              style={{ 
                padding: '4px', 
                fontSize: '10px', 
                background: '#3498db', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              <Plus size={12} />
            </button>
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              ✕
            </button>
            <button 
              onClick={deleteCurrentLine} 
              title="删除当前行"
              style={{ 
                padding: '4px', 
                fontSize: '10px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '24px',
                height: '24px'
              }}
            >
              <Trash2 size={12} />
            </button>
          </div>
        )
      }
    }
    
    // 如果是人员字段且包含多行内容，使用特殊的显示逻辑
    const isPersonnelField = key.includes('.responsible') || key.includes('.participants')
    const lines = value ? value.split('\n').filter(line => line.trim()) : []
    
    let displayContent
    if (isPersonnelField) {
      // 对于人员字段，如果有多行，每行自动编号，但保持每行内的多人用逗号分隔
      displayContent = lines.length > 1 
        ? lines.map((line, index) => `${index + 1}. ${line}`).join('\n')
        : value || ''
    } else {
      // 对于其他字段，如果包含多行内容，自动添加序号
      displayContent = lines.length > 1 
        ? lines.map((line, index) => `${index + 1}. ${line}`).join('\n')
        : value || ''
    }
    
    return (
      <div 
        onClick={() => startEdit(key)}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: '#333',
          fontSize: '14px',
          whiteSpace: 'pre-line'
        }}
        title="点击编辑"
      >
        {displayContent}
      </div>
    )
  }

  // 渲染只读单元格（用于总览页面）
  const renderReadOnlyCell = (key) => {
    const value = getValueByKey(key)
    
    if (!value) {
      return (
        <div style={{ 
          minHeight: '20px', 
          padding: '4px',
          color: '#333',
          whiteSpace: 'pre-line',
          fontSize: '14px'
        }}>
          {''}
        </div>
      )
    }
    
    // 如果包含多行内容，自动添加序号
    const lines = value.split('\n').filter(line => line.trim())
    const displayContent = lines.length > 1 
      ? lines.map((line, index) => `${index + 1}. ${line}`).join('\n')
      : value
    
    return (
      <div style={{ 
        minHeight: '20px', 
        padding: '4px',
        color: '#333',
        whiteSpace: 'pre-line',
        fontSize: '14px'
      }}>
        {displayContent}
      </div>
    )
  }

  // 渲染人员字段（负责人、执行人）- 支持单个项目多人
  const renderPersonnelCell = (key) => {
    const value = getValueByKey(key)
    
    if (!value) {
      return (
        <div style={{ 
          minHeight: '20px', 
          padding: '4px',
          color: '#333',
          whiteSpace: 'pre-line',
          fontSize: '14px'
        }}>
          {''}
        </div>
      )
    }
    
    // 处理多行内容，每行可能包含多个人员（用逗号分隔）
    const lines = value.split('\n').filter(line => line.trim())
    const displayContent = lines.length > 1 
      ? lines.map((line, index) => {
          // 如果一行中有多个人员（用逗号分隔），保持原格式
          return `${index + 1}. ${line}`
        }).join('\n')
      : value
    
    return (
      <div style={{ 
        minHeight: '20px', 
        padding: '4px',
        color: '#333',
        whiteSpace: 'pre-line',
        fontSize: '14px'
      }}>
        {displayContent}
      </div>
    )
  }

  // 渲染值班人员单元格（分为9点-21点和21点-9点）
  const renderDutyCell = (key) => {
    const value = getValueByKey(key)
    const dutyPersons = value ? value.split('\n').filter(person => person.trim()) : []
    
    // 格式化显示多个人员
    const formatPersons = (personsStr) => {
      if (!personsStr) return ''
      const persons = personsStr.split(',').map(p => p.trim()).filter(p => p)
      return persons.join('、')
    }
    
    return (
      <div style={{ 
        minHeight: '40px', 
        padding: '4px',
        color: '#333',
        fontSize: '12px',
        display: 'flex',
        flexDirection: 'column',
        gap: '2px'
      }}>
        <div style={{ borderBottom: '1px solid #eee', paddingBottom: '2px' }}>
          <strong>9点-21点：</strong>
          <div>{formatPersons(dutyPersons[0])}</div>
        </div>
        <div>
          <strong>21点-9点：</strong>
          <div>{formatPersons(dutyPersons[1])}</div>
        </div>
      </div>
    )
  }

  // 渲染可编辑的值班人员单元格（分为9点-21点和21点-9点）
  const renderDutyEditableCell = (key, selectOptions = []) => {
    const isEditing = editingCell === key
    const value = getValueByKey(key)
    const dutyPersons = value ? value.split('\n').filter(person => person.trim()) : []
    
    if (isEditing) {
      return (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: '2px' }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <div style={{ marginBottom: '4px' }}>
              <label style={{ fontSize: '11px', fontWeight: 'bold' }}>9点-21点：</label>
              <textarea
                value={editValue.split('\n')[0] || ''}
                onChange={(e) => {
                  const lines = editValue.split('\n')
                  lines[0] = e.target.value
                  setEditValue(lines.join('\n'))
                }}
                onFocus={(e) => setCurrentFocusedTextarea(e.target)}
                placeholder="请选择9点-21点值班人员（多人用逗号分隔）"
                rows={Math.max(1, (editValue.split('\n')[0] || '').split(',').length)}
                style={{ 
                  width: '100%', 
                  padding: '2px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '4px',
                  fontSize: '12px',
                  resize: 'vertical',
                  minHeight: '20px'
                }}
              />
            </div>
            <div>
              <label style={{ fontSize: '11px', fontWeight: 'bold' }}>21点-9点值班人：</label>
              <textarea
                value={editValue.split('\n')[1] || ''}
                onChange={(e) => {
                  const lines = editValue.split('\n')
                  lines[1] = e.target.value
                  setEditValue(lines.join('\n'))
                }}
                onFocus={(e) => setCurrentFocusedTextarea(e.target)}
                placeholder="请选择21点-9点值班人员（多人用逗号分隔）"
                rows={Math.max(1, (editValue.split('\n')[1] || '').split(',').length)}
                style={{ 
                  width: '100%', 
                  padding: '2px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '4px',
                  fontSize: '12px',
                  resize: 'vertical',
                  minHeight: '20px'
                }}
              />
            </div>
            {selectOptions.length > 0 && (
              <div style={{
                position: 'absolute',
                top: '100%',
                left: 0,
                right: 0,
                background: 'white',
                border: '1px solid #d9d9d9',
                borderTop: 'none',
                borderRadius: '0 0 4px 4px',
                maxHeight: '120px',
                overflowY: 'auto',
                zIndex: 1000,
                fontSize: '12px'
              }}>
                <div style={{ padding: '4px 8px', fontSize: '10px', color: '#666', borderBottom: '1px solid #f0f0f0' }}>
                  点击人员添加到当前焦点时段
                </div>
                {selectOptions.map(option => (
                  <div
                    key={option.value}
                    onClick={() => {
                      const lines = editValue.split('\n')
                      
                      // 判断当前焦点在哪个时段
                      let targetIndex = 0
                      
                      // 使用记录的焦点textarea来判断时段
                      if (currentFocusedTextarea && currentFocusedTextarea.placeholder) {
                        if (currentFocusedTextarea.placeholder.includes('21点-9点')) {
                          targetIndex = 1
                        } else if (currentFocusedTextarea.placeholder.includes('9点-21点')) {
                          targetIndex = 0
                        }
                      } else {
                        targetIndex = 0
                      }
                      
                      // 确保数组有足够的元素
                      while (lines.length <= targetIndex) {
                        lines.push('')
                      }
                      
                      // 添加人员到对应时段（用逗号分隔）
                      if (lines[targetIndex].trim() === '') {
                        lines[targetIndex] = option.value
                      } else {
                        // 检查是否已经存在该人员
                        const existingPersons = lines[targetIndex].split(',').map(p => p.trim())
                        if (!existingPersons.includes(option.value)) {
                          lines[targetIndex] = lines[targetIndex] + ',' + option.value
                        }
                      }
                      
                      setEditValue(lines.join('\n'))
                    }}
                    style={{
                      padding: '4px 8px',
                      cursor: 'pointer',
                      borderBottom: '1px solid #f0f0f0'
                    }}
                    onMouseEnter={(e) => e.target.style.background = '#f5f5f5'}
                    onMouseLeave={(e) => e.target.style.background = 'white'}
                  >
                    {option.label}
                  </div>
                ))}
              </div>
            )}
          </div>
          <button 
            onClick={saveEdit} 
            title="保存"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#27ae60', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            ✓
          </button>
          <button 
            onClick={cancelEdit} 
            title="取消"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#e74c3c', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            ✕
          </button>
        </div>
      )
    }
    
    return (
      <div 
        onClick={() => startEdit(key)}
        style={{ 
          cursor: 'pointer', 
          minHeight: '40px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: '#333',
          fontSize: '12px',
          display: 'flex',
          flexDirection: 'column',
          gap: '2px'
        }}
        title="点击编辑"
      >
        <div style={{ borderBottom: '1px solid #eee', paddingBottom: '2px' }}>
          <strong>9点-21点值班人：</strong>
          <div>{dutyPersons[0] || ''}</div>
        </div>
        <div>
          <strong>21点-9点值班人：</strong>
          <div>{dutyPersons[1] || ''}</div>
        </div>
      </div>
    )
  }

  // 渲染通用编辑单元格（用于总览页面所有字段）
  const renderGeneralEditCell = (key, selectOptions = [], placeholder = '点击编辑') => {
    const isEditing = editingCell === key
    const value = getValueByKey(key)
    const hasPersonnelOptions = selectOptions.length > 0
    
    if (isEditing) {
      return (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: '2px' }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <textarea
              ref={setTextareaRef}
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              placeholder={hasPersonnelOptions ? "请选择人员或输入内容" : "请输入内容"}
              rows={Math.max(1, editValue.split('\n').length)}
              style={{ 
                width: '100%', 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '14px',
                resize: 'vertical',
                minHeight: '20px'
              }}
            />
            {hasPersonnelOptions && (
              <div style={{
                position: 'absolute',
                top: '100%',
                left: 0,
                right: 0,
                background: 'white',
                border: '1px solid #d9d9d9',
                borderTop: 'none',
                borderRadius: '0 0 4px 4px',
                maxHeight: '120px',
                overflowY: 'auto',
                zIndex: 1000,
                fontSize: '14px'
              }}>
                {selectOptions.map(option => (
                  <div
                    key={option.value}
                    onClick={() => {
                      const currentLines = editValue.split('\n')
                      const lastLine = currentLines[currentLines.length - 1]
                      
                      if (lastLine.trim() === '') {
                        // 如果最后一行是空的，替换它
                        currentLines[currentLines.length - 1] = option.value
                      } else {
                        // 如果最后一行有内容，添加新行
                        currentLines.push(option.value)
                      }
                      
                      setEditValue(currentLines.join('\n'))
                    }}
                    style={{
                      padding: '4px 8px',
                      cursor: 'pointer',
                      borderBottom: '1px solid #f0f0f0'
                    }}
                    onMouseEnter={(e) => e.target.style.background = '#f5f5f5'}
                    onMouseLeave={(e) => e.target.style.background = 'white'}
                  >
                    {option.label}
                  </div>
                ))}
              </div>
            )}
          </div>
          <button 
            onClick={addToContent} 
            title="添加行"
            style={{ 
              padding: '4px', 
              fontSize: '10px', 
              background: '#3498db', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            <Plus size={12} />
          </button>
          <button 
            onClick={saveEdit} 
            title="保存"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#27ae60', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            ✓
          </button>
          <button 
            onClick={cancelEdit} 
            title="取消"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#e74c3c', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            ✕
          </button>
          <button 
            onClick={deleteCurrentLine} 
            title="删除当前行"
            style={{ 
              padding: '4px', 
              fontSize: '10px', 
              background: '#e74c3c', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '24px',
              height: '24px'
            }}
          >
            <Trash2 size={12} />
          </button>
        </div>
      )
    }
    
    return (
      <div 
        onClick={() => startEdit(key)}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: '#333',
          fontSize: '14px',
          whiteSpace: 'pre-line'
        }}
        title="点击编辑"
      >
        {value || ''}
      </div>
    )
  }

  const recentDates = getRecentDates()
  const dates = getDisplayDates()
  const personnelOptions = personnel.map(p => ({ value: p.name, label: p.name }))

  return (
    <div className="card">
      {/* 错误提示 */}
      {error && (
        <div style={{
          marginBottom: '20px',
          padding: '12px',
          background: '#f8d7da',
          border: '1px solid #f5c6cb',
          borderRadius: '4px',
          color: '#721c24'
        }}>
          <strong>错误：</strong>{error}
          <button 
            onClick={() => setError(null)}
            style={{
              marginLeft: '10px',
              padding: '2px 8px',
              background: 'transparent',
              border: '1px solid #721c24',
              borderRadius: '3px',
              color: '#721c24',
              cursor: 'pointer'
            }}
          >
            关闭
          </button>
        </div>
      )}
      

      
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <h2>日工作计划安排</h2>
        <div style={{ display: 'flex', gap: '8px' }}>
          <button
            onClick={handlePushToDingTalk}
            disabled={loading}
            style={{
              padding: '8px 16px',
              background: loading ? '#6c757d' : '#17a2b8',
              border: `1px solid ${loading ? '#6c757d' : '#17a2b8'}`,
              borderRadius: '6px',
              cursor: loading ? 'not-allowed' : 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="提交当前选项卡和当前日期的工作计划到钉钉群"
          >
            <Send size={16} />
            提交
          </button>
          <button
            onClick={handleSaveAllData}
            disabled={loading}
            style={{
              padding: '8px 16px',
              background: loading ? '#6c757d' : '#007bff',
              border: `1px solid ${loading ? '#6c757d' : '#007bff'}`,
              borderRadius: '6px',
              cursor: loading ? 'not-allowed' : 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="保存所有数据到数据库"
          >
            <Save size={16} />
            保存
          </button>
          <button
            onClick={exportToExcel}
            style={{
              padding: '8px 16px',
              background: '#28a745',
              border: '1px solid #28a745',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="导出当前数据到Excel"
          >
            <Download size={16} />
            导出Excel
          </button>
        </div>
      </div>

      {/* 日期选择器 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'block', marginBottom: '8px', fontWeight: '600' }}>选择日期:</label>
        <div style={{ position: 'relative', display: 'inline-block' }}>
          <button
            onClick={() => setShowCalendar(!showCalendar)}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              padding: '8px 12px',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              background: 'white',
              cursor: 'pointer',
              fontSize: '14px',
              minWidth: '200px'
            }}
          >
            <Calendar size={16} />
            <span>
              {selectedDates.length > 0 
                ? `已选择 ${selectedDates.length} 个日期`
                : '选择日期范围'
              }
            </span>
          </button>
          {showCalendar && (
            <div style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              background: 'white',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              padding: '16px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
              zIndex: 1000,
              minWidth: '320px'
            }}>
              {/* 日历头部 */}
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '16px'
              }}>
                <button
                  onClick={() => setCalendarMonth(new Date(calendarMonth.getFullYear(), calendarMonth.getMonth() - 1))}
                  style={{
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    padding: '4px'
                  }}
                >
                  <ChevronLeft size={20} />
                </button>
                <span style={{ fontSize: '16px', fontWeight: '600' }}>
                  {calendarMonth.getFullYear()}年 {['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'][calendarMonth.getMonth()]}
                </span>
                <button
                  onClick={() => setCalendarMonth(new Date(calendarMonth.getFullYear(), calendarMonth.getMonth() + 1))}
                  style={{
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    padding: '4px'
                  }}
                >
                  <ChevronRight size={20} />
                </button>
              </div>
              
              {/* 选择模式切换 */}
              <div style={{
                display: 'flex',
                gap: '8px',
                marginBottom: '16px'
              }}>
                <button
                  onClick={() => {
                    setIsRangeSelection(false)
                    clearSelection()
                  }}
                  style={{
                    padding: '4px 8px',
                    fontSize: '12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    background: !isRangeSelection ? '#3498db' : 'white',
                    color: !isRangeSelection ? 'white' : '#333',
                    cursor: 'pointer'
                  }}
                >
                  单选
                </button>
                <button
                  onClick={() => {
                    setIsRangeSelection(true)
                    clearSelection()
                  }}
                  style={{
                    padding: '4px 8px',
                    fontSize: '12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    background: isRangeSelection ? '#3498db' : 'white',
                    color: isRangeSelection ? 'white' : '#333',
                    cursor: 'pointer'
                  }}
                >
                  范围选择
                </button>
              </div>
              
              {/* 星期标题 */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(7, 1fr)',
                gap: '2px',
                marginBottom: '8px'
              }}>
                {['日', '一', '二', '三', '四', '五', '六'].map(day => (
                  <div key={day} style={{
                    textAlign: 'center',
                    fontSize: '12px',
                    fontWeight: '600',
                    color: '#666',
                    padding: '4px'
                  }}>
                    {day}
                  </div>
                ))}
              </div>
              
              {/* 日期网格 */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(7, 1fr)',
                gap: '2px',
                marginBottom: '16px'
              }}>
                {getDaysInMonth(calendarMonth).map((dayInfo, index) => {
                  const dayOfWeek = new Date(dayInfo.date).getDay()
                  const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
                  
                  return (
                    <button
                      key={index}
                      onClick={() => dayInfo.isCurrentMonth && handleDateClick(dayInfo.date)}
                      style={{
                        padding: '8px 4px',
                        fontSize: '12px',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: dayInfo.isCurrentMonth ? 'pointer' : 'default',
                        background: dayInfo.isSelected ? '#3498db' : 
                                  dayInfo.isInRange ? '#e3f2fd' :
                                  dayInfo.isToday ? '#f0f0f0' : 'transparent',
                        color: dayInfo.isSelected ? 'white' :
                              !dayInfo.isCurrentMonth ? '#ccc' :
                              isWeekend ? '#e74c3c' : '#333',
                        fontWeight: dayInfo.isToday ? '600' : 'normal'
                      }}
                    >
                      {dayInfo.day}
                    </button>
                  )
                })}
              </div>
              
              {/* 操作按钮 */}
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                gap: '8px'
              }}>
                <button
                  onClick={clearSelection}
                  style={{
                    padding: '6px 12px',
                    fontSize: '12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    background: 'white',
                    cursor: 'pointer'
                  }}
                >
                  清空
                </button>
                <div style={{ display: 'flex', gap: '8px' }}>
                  <button
                    onClick={() => setShowCalendar(false)}
                    style={{
                      padding: '6px 12px',
                      fontSize: '12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      background: 'white',
                      cursor: 'pointer'
                    }}
                  >
                    取消
                  </button>
                  <button
                    onClick={applySelection}
                    style={{
                      padding: '6px 12px',
                      fontSize: '12px',
                      border: 'none',
                      borderRadius: '4px',
                      background: '#3498db',
                      color: 'white',
                      cursor: 'pointer'
                    }}
                  >
                    确定
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
        {selectedDates.length > 0 && (
          <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
            选中日期: {selectedDates.sort().join(', ')}
          </div>
        )}
      </div>

      {/* 实验类型选项卡 */}
      <div style={{ marginBottom: '16px' }}>
        <div style={{ 
          display: 'flex', 
          borderBottom: '2px solid #f0f0f0',
          position: 'relative'
        }}>
          {experimentTypes.map(type => (
            <div
              key={type.key}
              onClick={() => setSelectedType(type.key)}
              style={{
                padding: '12px 20px',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: selectedType === type.key ? '600' : '500',
                color: selectedType === type.key ? type.color : '#666',
                borderBottom: selectedType === type.key ? `3px solid ${type.color}` : '3px solid transparent',
                marginBottom: '-2px',
                transition: 'all 0.3s ease',
                position: 'relative',
                background: selectedType === type.key ? `${type.color}08` : 'transparent',
                borderRadius: '4px 4px 0 0'
              }}
              onMouseEnter={(e) => {
                if (selectedType !== type.key) {
                  e.target.style.background = '#f8f9fa'
                  e.target.style.color = type.color
                }
              }}
              onMouseLeave={(e) => {
                if (selectedType !== type.key) {
                  e.target.style.background = 'transparent'
                  e.target.style.color = '#666'
                }
              }}
            >
              {type.label}
            </div>
          ))}
        </div>
      </div>

      {/* 总览 - 显示所有实验类型的表格 */}
      {selectedType === '总览' && (
        <div style={{ overflowX: 'auto' }}>
          <div style={{ display: 'flex', gap: '20px', minWidth: 'max-content' }}>
            {experimentTypes.filter(type => type.key !== '总览').map(type => (
              <div key={type.key} style={{ minWidth: '800px', flex: 'none' }}>
                {/* 实验类型标题 */}
                <div style={{
                  padding: '12px 16px',
                  backgroundColor: type.color,
                  color: 'white',
                  borderRadius: '8px 8px 0 0',
                  fontSize: '16px',
                  fontWeight: '600',
                  textAlign: 'center'
                }}>
                  {type.label}
                </div>
                
                {/* 表格 */}
                <div style={{
                  border: '1px solid #e9ecef',
                  borderTop: 'none',
                  borderRadius: '0 0 8px 8px',
                  backgroundColor: 'white',
                  overflow: 'visible'
                }}>
                  <table style={{
                    width: '100%',
                    borderCollapse: 'collapse',
                    fontSize: '14px'
                  }}>
                    <thead>
                      <tr style={{ backgroundColor: '#f8f9fa' }}>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>日期</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>试验项目</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>工作内容</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>开始时间</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>结束时间</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>负责人</th>
                        <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>执行人</th>
                        {type.key === '热学试验' && (
                          <>
                            <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>值班人（日）</th>
                            <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #f0f0f0' }}>值班人（夜）</th>
                          </>
                        )}
                      </tr>
                    </thead>
                    <tbody>
                      {(() => {
                        const typeProjects = projectData[type.key] || []
                        if (typeProjects.length === 0) {
                          return (
                            <tr>
                              <td colSpan={type.key === '热学试验' ? '9' : '7'} style={{ padding: '40px', textAlign: 'center', color: '#999' }}>
                                暂无{type.label}项目
                              </td>
                            </tr>
                          )
                        }
                        
                        // 按日期分组
                        const groupedByDate = {}
                        typeProjects.forEach(project => {
                          if (!groupedByDate[project.date]) {
                            groupedByDate[project.date] = []
                          }
                          groupedByDate[project.date].push(project)
                        })
                        
                        const rows = []
                        Object.keys(groupedByDate).sort().forEach(date => {
                          const projectsForDate = groupedByDate[date]
                          projectsForDate.forEach((project, projectIndex) => {
                            project.workItems.forEach((workItem, workIndex) => {
                              const isFirstRowForDate = projectIndex === 0 && workIndex === 0
                              const isFirstRowForProject = workIndex === 0
                              const totalRowsForDate = projectsForDate.reduce((sum, p) => sum + p.workItems.length, 0)
                              
                              rows.push(
                                <tr key={`${project.id}-${workIndex}`} style={{ borderBottom: '1px solid #f0f0f0' }}>
                                  {/* 日期列 */}
                                  {isFirstRowForDate && (() => {
                                    const dateObj = new Date(date)
                                    const dayOfWeek = dateObj.getDay()
                                    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6 // 0=周日, 6=周六
                                    
                                    return (
                                      <td 
                                        rowSpan={totalRowsForDate}
                                        style={{ 
                                          padding: '8px 12px', 
                                          borderRight: '1px solid #f0f0f0',
                                          textAlign: 'center',
                                          verticalAlign: 'middle',
                                          backgroundColor: '#fafafa',
                                          fontSize: '14px',
                                          fontWeight: '500'
                                        }}
                                      >
                                        <div style={{ lineHeight: '1.2' }}>
                                          <div style={{ color: isWeekend ? '#e74c3c' : 'inherit' }}>{date}</div>
                                          <div style={{ 
                                            fontSize: '12px', 
                                            color: isWeekend ? '#e74c3c' : '#666', 
                                            marginTop: '2px',
                                            fontWeight: 'normal'
                                          }}>
                                            {getWeekDay(date)}
                                          </div>
                                        </div>
                                      </td>
                                    )
                                  })()}
                                  
                                  {/* 试验项目列 */}
                                  {isFirstRowForProject && (
                                    <td 
                                      rowSpan={project.workItems.length}
                                      style={{ 
                                        padding: '8px 12px', 
                                        borderRight: '1px solid #f0f0f0',
                                        textAlign: 'center',
                                        verticalAlign: 'middle'
                                      }}
                                    >
                                      {project.project}
                                    </td>
                                  )}
                                  
                                  {/* 工作内容列 */}
                                  <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                                    {workItem.content}
                                  </td>
                                  
                                  {/* 开始时间列 */}
                                  <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                                    {workItem.start_time}
                                  </td>
                                  
                                  {/* 结束时间列 */}
                                  <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                                    {workItem.end_time}
                                  </td>
                                  
                                  {/* 负责人列 */}
                                  <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                                    {workItem.responsible}
                                  </td>
                                  
                                  {/* 执行人列 */}
                                  <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                                    {workItem.participants}
                                  </td>
                                  
                                  {/* 热学试验特有的值班人列 */}
                                  {type.key === '热学试验' && (
                                    <>
                                      {isFirstRowForDate && (
                                        <>
                                          <td 
                                            rowSpan={totalRowsForDate} 
                                            style={{ 
                                              padding: '8px 12px', 
                                              borderRight: '1px solid #f0f0f0',
                                              verticalAlign: 'middle',
                                              backgroundColor: '#fafafa',
                                              textAlign: 'center'
                                            }}
                                          >
                                            {project.duty_day}
                                          </td>
                                          <td 
                                            rowSpan={totalRowsForDate} 
                                            style={{ 
                                              padding: '8px 12px', 
                                              borderRight: '1px solid #f0f0f0',
                                              verticalAlign: 'middle',
                                              backgroundColor: '#fafafa',
                                              textAlign: 'center'
                                            }}
                                          >
                                            {project.duty_night}
                                          </td>
                                        </>
                                      )}
                                    </>
                                  )}
                                </tr>
                              )
                            })
                          })
                        })
                        
                        return rows
                      })()}
                    </tbody>
                  </table>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 单个实验类型表格 */}
      {selectedType !== '总览' && (
        <div>
          {/* 添加项目按钮 */}
          <div style={{ marginBottom: '16px' }}>
            <button
              onClick={() => addProject(selectedType)}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                padding: '8px 16px',
                backgroundColor: experimentTypes.find(t => t.key === selectedType)?.color,
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: '500'
              }}
            >
              <Plus size={16} />
              添加项目
            </button>
          </div>

          {/* 项目表格 */}
          <div style={{
            border: '1px solid #e9ecef',
            borderRadius: '8px',
            backgroundColor: 'white',
            overflow: 'visible'
          }}>
            <table style={{
              width: '100%',
              borderCollapse: 'collapse',
              fontSize: '14px'
            }}>
              <thead>
                <tr style={{ backgroundColor: '#f8f9fa' }}>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '120px' }}>日期</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '200px' }}>试验项目</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef' }}>工作内容</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '100px' }}>开始时间</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '100px' }}>结束时间</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '120px' }}>负责人</th>
                  <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '120px' }}>执行人</th>
                  {selectedType === '热学试验' && (
                    <>
                      <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '100px' }}>值班人(日)</th>
                      <th style={{ padding: '12px', textAlign: 'center', borderRight: '1px solid #e9ecef', width: '100px' }}>值班人(夜)</th>
                    </>
                  )}
                  <th style={{ padding: '12px', textAlign: 'center', width: '120px' }}>操作</th>
                </tr>
              </thead>
              <tbody>
                {(() => {
                  // 按日期分组项目
                  const projectsByDate = {}
                  projectData[selectedType].forEach(project => {
                    if (!projectsByDate[project.date]) {
                      projectsByDate[project.date] = []
                    }
                    projectsByDate[project.date].push(project)
                  })
                  
                  // 按日期排序
                  const sortedDates = Object.keys(projectsByDate).sort((a, b) => new Date(a) - new Date(b))
                  
                  const rows = []
                  sortedDates.forEach(date => {
                    const projectsForDate = projectsByDate[date]
                    const totalRowsForDate = projectsForDate.reduce((sum, p) => sum + p.workItems.length, 0)
                    
                    projectsForDate.forEach((project, projectIndex) => {
                      project.workItems.forEach((workItem, workIndex) => {
                        const isFirstRowForDate = projectIndex === 0 && workIndex === 0
                        const isFirstRowForProject = workIndex === 0
                        
                        rows.push(
                          <tr key={`${project.id}-${workIndex}`} style={{ borderBottom: '1px solid #f0f0f0' }}>
                            {/* 日期列 - 相同日期合并，不可编辑 */}
                            {isFirstRowForDate && (() => {
                              const dateObj = new Date(project.date)
                              const dayOfWeek = dateObj.getDay()
                              const isWeekend = dayOfWeek === 0 || dayOfWeek === 6 // 0=周日, 6=周六
                              
                              return (
                                <td 
                                  rowSpan={totalRowsForDate}
                                  style={{ 
                                    padding: '8px 12px', 
                                    borderRight: '1px solid #f0f0f0',
                                    textAlign: 'center',
                                    verticalAlign: 'middle',
                                    backgroundColor: '#fafafa',
                                    fontSize: '14px',
                                    fontWeight: '500'
                                  }}
                                >
                                  <div style={{ lineHeight: '1.2' }}>
                                    <div style={{ color: isWeekend ? '#e74c3c' : 'inherit' }}>{project.date}</div>
                                    <div style={{ 
                                      fontSize: '12px', 
                                      color: isWeekend ? '#e74c3c' : '#666', 
                                      marginTop: '2px',
                                      fontWeight: 'normal'
                                    }}>
                                      {getWeekDay(project.date)}
                                    </div>
                                  </div>
                                </td>
                              )
                            })()}
                            
                            {/* 试验项目列 - 每个项目合并 */}
                            {isFirstRowForProject && (
                              <td 
                                rowSpan={project.workItems.length} 
                                style={{ 
                                  padding: '8px 12px', 
                                  borderRight: '1px solid #f0f0f0',
                                  verticalAlign: 'middle',
                                  backgroundColor: '#fafafa',
                                  textAlign: 'center'
                                }}
                              >
                                <input
                                  type="text"
                                  value={project.project}
                                  onChange={(e) => updateProject(selectedType, project.id, 'project', e.target.value)}
                                  placeholder="输入试验项目名称"
                                  style={{
                                    border: 'none',
                                    background: 'transparent',
                                    fontSize: '14px',
                                    width: '100%',
                                    textAlign: 'center',
                                    height: '36px',
                                    padding: '8px'
                                  }}
                                />
                              </td>
                            )}
                            
                            {/* 工作内容列 */}
                            <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                              <input
                                type="text"
                                value={workItem.content}
                                onChange={(e) => updateWorkItem(selectedType, project.id, workIndex, 'content', e.target.value)}
                                placeholder="输入工作内容"
                                style={{
                                  border: 'none',
                                  background: 'transparent',
                                  fontSize: '14px',
                                  width: '100%',
                                  textAlign: 'center',
                                  height: '36px',
                                  padding: '8px'
                                }}
                              />
                            </td>
                            
                            {/* 开始时间列 */}
                            <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                              <input
                                type="datetime-local"
                                value={workItem.start_time || ''}
                                onChange={(e) => updateWorkItem(selectedType, project.id, workIndex, 'start_time', e.target.value)}
                                style={{
                                  border: '1px solid #d9d9d9',
                                  borderRadius: '4px',
                                  fontSize: '14px',
                                  width: '100%',
                                  textAlign: 'center',
                                  height: '36px',
                                  padding: '8px'
                                }}
                              />
                            </td>
                            
                            {/* 结束时间列 */}
                            <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                              <input
                                type="datetime-local"
                                value={workItem.end_time || ''}
                                onChange={(e) => updateWorkItem(selectedType, project.id, workIndex, 'end_time', e.target.value)}
                                style={{
                                  border: '1px solid #d9d9d9',
                                  borderRadius: '4px',
                                  fontSize: '14px',
                                  width: '100%',
                                  textAlign: 'center',
                                  height: '36px',
                                  padding: '8px'
                                }}
                              />
                            </td>
                            
                            {/* 负责人列 */}
                            <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                              <MultiSelect
                                options={personnel.map(p => ({ value: p.name, label: p.name }))}
                                value={workItem.responsible ? workItem.responsible.split(',').map(name => name.trim()) : []}
                                onChange={(selectedValues) => {
                                  updateWorkItem(selectedType, project.id, workIndex, 'responsible', selectedValues.join(', '))
                                }}
                                placeholder="选择负责人"
                              />
                            </td>
                            
                            {/* 执行人列 */}
                            <td style={{ padding: '8px 12px', borderRight: '1px solid #f0f0f0', textAlign: 'center' }}>
                              <MultiSelect
                                options={personnel.map(p => ({ value: p.name, label: p.name }))}
                                value={workItem.participants ? workItem.participants.split(',').map(name => name.trim()) : []}
                                onChange={(selectedValues) => {
                                  updateWorkItem(selectedType, project.id, workIndex, 'participants', selectedValues.join(', '))
                                }}
                                placeholder="选择执行人"
                              />
                            </td>
                            
                            {/* 热学试验特有的值班人列 */}
                            {selectedType === '热学试验' && (
                              <>
                                {isFirstRowForDate && (
                                  <>
                                    <td 
                                      rowSpan={totalRowsForDate} 
                                      style={{ 
                                        padding: '8px 12px', 
                                        borderRight: '1px solid #f0f0f0',
                                        verticalAlign: 'middle',
                                        backgroundColor: '#fafafa',
                                        textAlign: 'center'
                                      }}
                                    >
                                      <MultiSelect
                                        options={personnel.map(p => ({ value: p.name, label: p.name }))}
                                        value={project.duty_day ? project.duty_day.split(',').map(name => name.trim()) : []}
                                        onChange={(selectedValues) => {
                                          // 更新所有相同日期的项目的值班人(日)
                                          projectsForDate.forEach(p => {
                                            updateProject(selectedType, p.id, 'duty_day', selectedValues.join(', '))
                                          })
                                        }}
                                        placeholder="选择值班人(日)"
                                      />
                                    </td>
                                    <td 
                                      rowSpan={totalRowsForDate} 
                                      style={{ 
                                        padding: '8px 12px', 
                                        borderRight: '1px solid #f0f0f0',
                                        verticalAlign: 'middle',
                                        backgroundColor: '#fafafa',
                                        textAlign: 'center'
                                      }}
                                    >
                                      <MultiSelect
                                        options={personnel.map(p => ({ value: p.name, label: p.name }))}
                                        value={project.duty_night ? project.duty_night.split(',').map(name => name.trim()) : []}
                                        onChange={(selectedValues) => {
                                          // 更新所有相同日期的项目的值班人(夜)
                                          projectsForDate.forEach(p => {
                                            updateProject(selectedType, p.id, 'duty_night', selectedValues.join(', '))
                                          })
                                        }}
                                        placeholder="选择值班人(夜)"
                                      />
                                    </td>
                                  </>
                                )}
                              </>
                            )}
                            
                            {/* 操作列 */}
                            <td style={{ padding: '8px 12px', textAlign: 'center' }}>
                              <div style={{ display: 'flex', gap: '4px', justifyContent: 'center' }}>
                                {/* 只在每个项目的最后一行显示添加按钮 */}
                                {workIndex === project.workItems.length - 1 && (
                                  <button
                                    onClick={() => addWorkItem(selectedType, project.id)}
                                    style={{
                                      padding: '4px 8px',
                                      backgroundColor: '#28a745',
                                      color: 'white',
                                      border: 'none',
                                      borderRadius: '4px',
                                      cursor: 'pointer',
                                      fontSize: '12px'
                                    }}
                                    title="添加工作内容"
                                  >
                                    <Plus size={12} />
                                  </button>
                                )}
                                {/* 删除工作内容按钮：只在有多个工作内容且不是最后一行时显示 */}
                                {project.workItems.length > 1 && workIndex !== project.workItems.length - 1 && (
                                  <button
                                    onClick={() => removeWorkItem(selectedType, project.id, workIndex)}
                                    style={{
                                      padding: '4px 8px',
                                      backgroundColor: '#ffc107',
                                      color: 'white',
                                      border: 'none',
                                      borderRadius: '4px',
                                      cursor: 'pointer',
                                      fontSize: '12px'
                                    }}
                                    title="删除此工作内容"
                                  >
                                    <X size={12} />
                                  </button>
                                )}
                                {/* 删除项目按钮：只在第一行显示 */}
                                {isFirstRowForProject && (
                                  <button
                                    onClick={() => removeProject(selectedType, project.id)}
                                    style={{
                                      padding: '4px 8px',
                                      backgroundColor: '#dc3545',
                                      color: 'white',
                                      border: 'none',
                                      borderRadius: '4px',
                                      cursor: 'pointer',
                                      fontSize: '12px'
                                    }}
                                    title="删除整个项目"
                                  >
                                    <Trash2 size={12} />
                                  </button>
                                )}
                              </div>
                            </td>
                          </tr>
                        )
                      })
                    })
                  })
                  
                  return rows
                })()}
                {projectData[selectedType].length === 0 && (
                  <tr>
                    <td colSpan={selectedType === '热学试验' ? '10' : '8'} style={{ padding: '40px', textAlign: 'center', color: '#999' }}>
                      暂无项目，点击上方"添加项目"按钮开始添加
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}



      {personnel.length === 0 && (
        <div style={{ 
          marginTop: '20px', 
          padding: '16px', 
          background: '#fff3cd', 
          border: '1px solid #ffeaa7', 
          borderRadius: '4px',
          color: '#856404'
        }}>
          <strong>提示：</strong>请先在"信息维护"中添加人员信息，以便在此处选择试验负责人和值班人员。
        </div>
      )}
    </div>
  )
}

export default DailyWorkPlan